package top.chaileilei.zookeeper.curator;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.BackgroundCallback;
import org.apache.curator.framework.api.CuratorEvent;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Description
 * @Time 2019/2/12
 * @Author CHAILEILEI
 * @Weblog www.chaileilei.top
 */
public class AsyncCuratorDemo {
    private static CuratorFramework client = CuratorFrameworkFactory.builder()
            .connectString("119.27.189.174:2181")
            .sessionTimeoutMs(5000)
            .retryPolicy(new ExponentialBackoffRetry(1000, 3))
            .build();

    private static CountDownLatch countDownLatch = new CountDownLatch(2);
    private static ExecutorService executorService = Executors.newFixedThreadPool(2);


    public static void create() throws Exception {
         String path = "/sdf";
        client.start();
        client.create().creatingParentsIfNeeded()
                .withMode(CreateMode.EPHEMERAL).inBackground(new BackgroundCallback() {
            @Override
            public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                System.out.println("event[code: " + event.getResultCode() + ", type: " + event.getType() + "]");
                System.out.println("Thread of processResult: " + Thread.currentThread().getName());
                countDownLatch.countDown();
            }
        },executorService).forPath(path,"dfdg".getBytes());
        client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).inBackground(new BackgroundCallback() {
            @Override
            public void processResult(CuratorFramework client, CuratorEvent event) throws Exception {
                System.out.println("event[code: " + event.getResultCode() + ", type: " + event.getType() + "]");
                System.out.println("Thread of processResult: " + Thread.currentThread().getName());
                countDownLatch.countDown();
            }
        }).forPath(path,"dert".getBytes());
        countDownLatch.await();
        executorService.shutdown();
    }

}
